// 创建路由实例并配置路由规则并导出挂载到main.ts的app上 App.vue并准备路由出口
import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
import useStore from '@/store'
import Confirm from '@/components/confirm'
const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior(to, from, savedPosition) {
    // return { top: 0 } // 始终滚动到顶部
    // 刷新保留滚动条位置
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
  routes: [
    { path: '/', component: Layout, children: [
      { path: '', component: Home },
      { path: '/category/:id', component: ()=> import('@/views/category/index.vue') },
      { path: '/category/sub/:id', component: ()=> import('@/views/category/sub.vue') },
      { path: '/product/:id', component: ()=> import('@/views/goods/index.vue') },
      { path: '/cart', component: ()=> import('@/views/cart/index.vue') },
      { path: '/member/checkout', component: ()=> import('@/views/member/pay/checkout.vue') },
      { path: '/member/pay', component: ()=> import('@/views/member/pay/index.vue') },
      { path: '/pay/callback', component: ()=> import('@/views/member/pay/callback.vue') },
      { path: '/member', component: ()=> import('@/views/member/layout/index.vue'),
      children: [
        {path: '', component: ()=>import('@/views/member/home/index.vue')},
        {path: 'order', component: ()=>import('@/views/member/order/index.vue')},
      ]
    },
    ] },
    { path: '/login', component: () => import('@/views/login/index.vue') },
    { path: '/playground', component: () => import('@/views/playground/index.vue') },
    { path: '/login/callback', component: () => import('@/views/login/callback.vue') }

  ]
})
// 添加前置导航守卫
// to 要去哪
// from 从哪来
// next() 放行函数  使用和router.push() push方法中可以写什么, next()也可以写什么
// router.push('/路径')
// router.push({path: '/路径', query: {}})
// router.push({name: name名称, params: {}})
router.beforeEach((to, from, next)=> {
  console.log(to)
  
  // 先判断是否登录了 如果登录了想去哪就去哪
  const { cart } = useStore()
  if(cart.isLogin) {
    next()
  }else {
    // 没有登录 除了包含/member 路径的 这些页面不能访问(先去登录), 别的页面随便访问
    // includes  
    if(to.path.indexOf('/member') !== -1) {
    // if(to.path.includes('/member')) {
      Confirm({title: '温馨提示', text: '亲,下单结算前确认登录么?'})
      .then( () => {
        next({
          path: '/login',
          query: {redirectUrl: to.fullPath}
        })
      }).catch( () => { } )
    }else {
      next()
    }
  }
})


export default router
// 1. 安装路由 yarn add vue-router 
// 2. router/index.ts 
// 3. 新建views对应的组件 layout  login
// 4. main.ts挂载
// 5. 准备路由出口